//
//  CLImagePickerController.m
//  CLImagePicker
//
//  Created by Criss on 2017/3/17.
//  Copyright © 2017年 Criss. All rights reserved.
//

#import "CLImagePickerController.h"
#import "CLImageCollectionView.h"

@interface CLImagePickerController () <CLImageCollectionViewShowAlertDelegate>

@property (strong, nonatomic) NSArray *imageArray;

@end

@implementation CLImagePickerController {
    CLImageCollectionView *_imageCollectionView;
}

+ (instancetype)imagePickerWithImageArray:(NSArray *)imageArray {
    CLImagePickerController *imagePickerVC = [[self alloc] init];
    imagePickerVC.imageArray = imageArray;
    return imagePickerVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    if (self.navigationController) {
        UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
        self.navigationItem.leftBarButtonItem = back;
        self.navigationItem.title = @"我的相册";
        self.navigationController.navigationBar.tintColor = [UIColor blackColor];
        
        UIBarButtonItem *select = [[UIBarButtonItem alloc] initWithTitle:@"选择" style:UIBarButtonItemStylePlain target:self action:@selector(selectPhotos)];
        self.navigationItem.rightBarButtonItem = select;
        
    }
    if (DEBUG) {
        NSLog(@"%@", self.imageArray);
    }
    _imageCollectionView = [CLImageCollectionView collectionWithImageArray:self.imageArray];
    _imageCollectionView.showAlertDelegate = self;
    _imageCollectionView.imageDicM = self.imagesSelectedDic.mutableCopy;
    _imageCollectionView.sortOrder = self.imageSortArray.mutableCopy;
    _imageCollectionView.imageCounts = self.imageCounts;
    _imageCollectionView.originalImagesCounts = self.originalImagesCounts;
    _imageCollectionView.frame = self.view.frame;
    [self.view addSubview:_imageCollectionView];
    
}

- (void)back {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)selectPhotos {
    [self dismissViewControllerAnimated:YES completion:nil];
    if (self.imageSelectedBlock) {
        self.imageSelectedBlock(_imageCollectionView.imageDicM.copy, _imageCollectionView.sortOrder.copy);
    }
}

#pragma mark - CLImageCollectionViewShowAlertDelegate
- (void)imageCollectionView:(CLImageCollectionView *)imageCollectionView {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"最多只能添加%zd张图片", _imageCounts] message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alert dismissViewControllerAnimated:YES completion:nil];
    }];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

@end
